<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
  <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
  <title>注册</title>
  <link rel="stylesheet" type="text/css" href="../css/api.css" />
  <link rel="stylesheet" type="text/css" href="../css/register.css" />
</head>

<body>
  <div id="app" v-cloak>
    <div class="wrap flex-wrap flex-vertical">
      <header id="header">
        <div class="header-wrap">
          <div @click="goback" class="header-left">
            <i class="iconfont icon-pre"></i>
          </div>
          <div class="header-title">注册</div>
        </div>
      </header>
      <div id="main" class="flex-con">
        <div class="avatar-wrap">
          <div class="avatar" @click="showActionSheet">
            <img :src="avatar_img" alt="">
            <div class="tips">更换头像</div>
          </div>
        </div>
        <div class="form-wrap">
          <div class="form-item flex-wrap">
            <i class="iconfont icon-user"></i>
            <input v-model="name" class="flex-con" type="text" placeholder="请输入昵称">
          </div>
          <div class="form-item flex-wrap sex-wrap">
            <label v-for="(item, i) in sex" :key="i" @click="selectSex(i)" :class="['sex', 'sex' + i, sexIndex == i ? 'active' : '']">
              <i :class="['iconfont', 'icon-sex' + (i+1)]"></i>{{item.label}}
            </label>
          </div>
          <div class="btn-wrap">
            <button @click="register" id="submit-btn" type="button" :disabled="isDisabled" :class="[!isDisabled ? 'btn-active' : 'btn']">注册</button>
          </div>
        </div>
        <div v-if="FNImageClipShow" class="FNImageClip-control">
          <span @click="FNImageClip_cancel">取消</span>
          <span @click="FNImageClip_enter">确定</span>
        </div>
      </div>
    </div>
  </div>
</body>

</html>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/vue.js"></script>
<script type="text/javascript" src="../script/common.js"></script>
<script type="text/javascript">
  var app, FNImageClip;
  apiready = function () {
    $api.fixStatusBar($api.dom('#header'));
    api.setStatusBarStyle({
      style: 'light',
    });
    FNImageClip = api.require('FNImageClip');
    app = new Vue({
      el: '#app',
      data: {
        name: '',
        avatar: 'w.png',
        avatar_img: qiniuImageUrl + 'w.png',
        isDisabled: true,
        sex: [{
          label: '男生',
          value: '1'
        }, {
          label: '女生',
          value: '2'
        }],
        sexIndex: 0,
        qiniuToken: '',
        FNImageClipShow: false,
      },
      created: function () {
        var _this = this
        if (!!$api.getStorage('uid')) {
          api.openWin({
            name: 'main',
            url: 'main.html',
            slidBackEnabled: false
          });
        }
        _this.getQiniuToken();
        api.addEventListener({
          name: 'keyback'
        }, function(ret, err){
          api.closeWin();
        });
      },
      mounted: function () {},
      methods: {
        watchModel: function () {
          if (this.name == '') {
            this.isDisabled = true;
          } else {
            this.isDisabled = false;
          }
        },
        
        goback: function () {
          api.closeWin();
        },

        // 获取七牛token
        getQiniuToken: function () {
          var _this = this;
          api.ajax({
            url: baseUrl + 'qiniu/token',
            method: 'get',
            headers: {
              token: $api.getStorage('deviceToken')
            },
            data: {
              values: {
                uid: $api.getStorage('uid')
              }
            }
          }, function (ret, err) {
            if (ret.status == 200) {
              _this.qiniuToken = ret.data[0];
            }
          })
        },

        showActionSheet: function () {
          var _this = this;
          api.actionSheet({
            title: '',
            cancelTitle: '取消',
            destructiveTitle: '',
            buttons: ['拍照', '相册']
          }, function (ret, err) {
            if (ret) {
              if (ret.buttonIndex == 1) {
                _this.getImageFile('camera');
              }
              if (ret.buttonIndex == 2) {
                _this.getImageFile('library');
              }
            }
          });
        },

        getImageFile: function (type) {
          var _this = this;
          api.getPicture({
            sourceType: type,
            encodingType: 'png',
            mediaValue: 'pic',
            destinationType: 'url',
            allowEdit: false,
            saveToPhotoAlbum: false
          }, function (ret, err) {
            if (ret) {
              FNImageClip.open({
                rect: {
                  x: 0,
                  y: 0,
                  w: api.winWidth,
                  h: api.winHeight - 50
                },
                srcPath: ret.data,
                style: {
                  mask: 'rgba(0,0,0,0.5)',
                  clip: {
                    w: api.winWidth - 2,
                    h: api.winWidth - 2,
                    x: 1,
                    y: (api.winHeight - api.winWidth - 50) / 2,
                    borderColor: '#0f0',
                    borderWidth: 1,
                    appearance: 'rectangle'
                  }
                },
                mode: 'image',
                fixedOn: api.frameName
              }, function (ret, err) {
                if (ret.status) {
                  _this.FNImageClipShow = true;
                }
              });
            }
          });
        },

        FNImageClip_cancel: function () {
          this.FNImageClipShow = false;
          FNImageClip.close();
        },

        FNImageClip_enter: function () {
          var _this = this;
          api.showProgress({
            title: '',
            text: ''
          });
          FNImageClip.save({
            destPath: 'fs://imageClip/liaola_' + (+new Date()) + '.png',
            copyToAlbum: false,
            quality: 1
          }, function (ret, err) {
            if (ret) {
              if (ret.destPath == undefined) {
                api.hideProgress();
                api.toast({
                  msg: '图片保存失败'
                })
                this.FNImageClipShow = false;
                FNImageClip.close();
              } else {
                _this.uploadImg(ret.destPath)
              }
            } else {
              api.hideProgress();
              api.toast({
                msg: '图片保存失败'
              })
              this.FNImageClipShow = false;
              FNImageClip.close();
            }
          });
        },

        // 上传图片
        uploadImg: function (fileUrl) {
          var _this = this;
          api.ajax({
            url: qiniuBaseUrl,
            method: 'post',
            data: {
              values: {
                token: this.qiniuToken
              },
              files: {
                file: fileUrl
              }
            }
          }, function (ret, err) {
            api.hideProgress();
            if (ret) {
              _this.FNImageClipShow = false;
              FNImageClip.close();
              _this.avatar = ret.key;
              _this.avatar_img = qiniuImageUrl + ret.key;
            }
            if (err) {
              api.alert({
                title: 'title', 
                msg: JSON.stringify(err)
              });
              api.toast({
                msg: '网络错误，请稍后再试',
                duration: 2000,
                location: 'bottom'
              });
            }
          });
        },

        selectSex: function (index) {
          this.sexIndex = index;
          if (this.avatar == 'w.png' || this.avatar == 'm.png') {
            if (this.sexIndex == 0) {
              this.avatar = 'w.png';
              this.avatar_img = qiniuImageUrl + 'w.png';
            }
            if (this.sexIndex == 1) {
              this.avatar = 'm.png';
              this.avatar_img = qiniuImageUrl + 'm.png';
            }
          }
        },

        register: function () {
          var _this = this;
          if (_this.name == '') {
            api.toast({
              msg: '请填写一个昵称',
              duration: 2000,
              location: 'bottom'
            });
            return false;
          }
          api.showProgress({
            title: '',
            text: '正在注册...'
          });
          api.ajax({
            url: baseUrl + 'oauth/reg',
            method: 'post',
            headers: {
              token: $api.getStorage('deviceToken')
            },
            data: {
              values: {
                mobile: api.pageParam.mobile,
                password: api.pageParam.password,
                code: api.pageParam.code,
                sex: _this.sex[_this.sexIndex].value,
                avatar: _this.avatar,
                name: _this.name,
                channel: $api.getStorage('channel'),
                tuid: api.pageParam.invit_code,
              },
            }
          }, function (ret, err) {
            api.hideProgress();
            if (ret) {
              api.toast({
                msg: ret.message[0]
              });
              if (ret.status == 200) {
                var token = JSON.parse(ret.data.token).code == 200 ? JSON.parse(ret.data.token).token : '';
                $api.setStorage('uid', ret.data.id);
                $api.setStorage('uname', ret.data.name);
                $api.setStorage('uavatar', ret.data.avatar);
                $api.setStorage('umobile', ret.data.email);
                $api.setStorage('token', token);
                api.openWin({
                  name: 'main',
                  url: 'main.html',
                  slidBackEnabled: false
                });
              }
            }
            if (err) {
              api.toast({
                msg: '网络错误，请稍后再试'
              });
            }
          });
        },

      },
      watch: {
        'name': function () {
          this.watchModel()
        },
      }
    })
  }
</script>